import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { xSessionId } from '@/utils/utils'

const http = axios.create({
  baseURL: __SITE_CONFIG__.apiUrl,
  headers: {
    'Content-Type': 'application/json',
  },
})

http.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (['/user/passport/login', '/user/passport/register'].indexOf(config.url) === -1) {
      config.headers['Authorization'] = token ? `Bearer ${token}` : ''
    }
    config.headers['X-Session-Id'] = xSessionId.get()
    config.withCredentials = true
    console.log(config.method, ':', config.url)
    return config
  },
  (error) => {
    // 请求错误处理
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  (response) => {
    if (response.headers['x-session-id']) {
      xSessionId.set(response.headers['x-session-id'])
    }
    if (response.data.errcode === 0) {
      return response.data //成功
    } else {
      if (response.data.errcode === 1) {
        //警告
        ElMessage.warning(response.data.errmsg)
      } else if (response.data.errcode === 2) {
        //错误
        ElMessage.error(response.data.errmsg)
      }
      return Promise.reject(response.data) //错误信息
    }
  },
  (error) => {
    let errMsg = ''
    if (error.response.data && error.response.data.errmsg) {
      errMsg = error.response.data.errmsg
    }
    // 处理未授权错误
    if (error.response.status === 401) {
      ElMessage.error(errMsg ? errMsg : '未登录或登录已失效')
      console.error('Unauthorized')
      const authStore = useAuthStore()
      authStore.clear() //清除登录信息
      // 可以重定向到登录页面
    } else if (error.response.status === 403) {
      ElMessage.error(errMsg ? errMsg : '权限不足')
    } else if (error.response.status === 404) {
      ElMessage.error(errMsg ? errMsg : '请求不存在')
    } else if (error.response.status !== 200) {
      ElMessage.error(errMsg ? errMsg : '系统错误')
    }
    console.error('api error', error)
    return Promise.reject(error)
  }
)

export default http
